package com.zj.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class Resources {
    //包装类加载器，加载类时尝试用多种类加载器来加载。
    private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();
    private static Charset charset;
    public static Class<?> classForName(String className) throws ClassNotFoundException {
        return classLoaderWrapper.classForName(className);
    }

    public static Reader getResourceAsReader(String resource) throws IOException {
        InputStreamReader reader;
        if (charset == null) {
            reader = new InputStreamReader(getResourceAsStream(resource));
        } else {
            reader = new InputStreamReader(getResourceAsStream(resource), charset);
        }

        return reader;
    }

    public static InputStream getResourceAsStream(String resource) throws IOException {
        //可简易实现如下
//        return Resources.class.getClassLoader().getResourceAsStream(resource);
        return getResourceAsStream((ClassLoader)null, resource);
    }
//用多种类加载器来加载资源
    public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
        InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
        if (in == null) {
            throw new IOException("Could not find resource " + resource);
        } else {
            return in;
        }
    }
}
